package cn.mbz.blog.admin.webapi.service;


import cn.mbz.blog.admin.service.IAdminService;
import cn.mbz.blog.admin.webapi.mapper.AdminMapper;
import cn.mbz.blog.commons.exception.ServiceException;
import cn.mbz.blog.commons.pojo.dto.AdminSimpleDTO;
import cn.mbz.blog.commons.pojo.vo.AdminSimpleVO;
import cn.mbz.blog.commons.pojo.vo.RoleSimpleVO;
import cn.mbz.blog.commons.web.State;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class AdminServiceImpl implements IAdminService {

    @Autowired
    AdminMapper mapper;
    /**
     * 添加管理员
     * @param adminSimpleDTO
     */
    @Override
    public void addAdmin(AdminSimpleDTO adminSimpleDTO) {
        log.debug("开始添加管理员信息");
        log.debug("根据名字查询该管理员是否已经存在");
        AdminSimpleVO queryAdmin = mapper.getAdminByName(adminSimpleDTO.getName());
        log.debug("判断查询结果是否为空");
        if (queryAdmin != null){
            log.warn("管理员已存在,抛出异常");
            throw new ServiceException(State.ERR_ADMIN_EXIST,"该用户名已经存在!");
        }
        log.debug("管理员不存在,添加管理员");
        mapper.insertAdmin(adminSimpleDTO);
    }

    @Override
    public void addAdminRole(String adminName, String roleName) {
        log.debug("添加管理员对应角色");
        AdminSimpleVO queryAdmin = mapper.getAdminByName(adminName);
        RoleSimpleVO queryRole = mapper.getRoleByName(roleName);
        Long queryAdminId = queryAdmin.getId();
        Long queryRoleId = queryRole.getId();
        log.debug("查询出来的adminNameId = {},roleNameId = {}",queryAdminId,queryRoleId);
        log.debug("根据id查询该对应关系");
        Long adminRoleId = mapper.getIdByAdminIdAndRoleId(queryAdminId,queryRoleId);
        log.debug("查询对应的关系是否存在");
        if (adminRoleId != null){
            log.warn("该对应关系以及存在抛出异常");
            throw new ServiceException(State.ERR_ADMIN_ROLE_EXIST,"该管理员对应角色关系已经存在");
        }
        log.debug("对应的关系不存在,添加对应关系");
        mapper.insertAdminRole(queryAdminId,queryRoleId);


    }
}
